package com.taijihuabao.common.activititasklistener.leavelistener;

import com.alibaba.excel.util.CollectionUtils;
import com.taijihuabao.modules.entity.ApprovalEntity;
import com.taijihuabao.modules.entity.ApprovalHistoryEntity;
import com.taijihuabao.modules.entity.DeptUserEntity;
import com.taijihuabao.modules.enums.optenums.dept.DeptRoleEnum;
import com.taijihuabao.modules.mapper.ApprovalHistoryMapper;
import com.taijihuabao.modules.mapper.ApprovalMapper;
import com.taijihuabao.modules.mapper.DeptUserMapper;
import com.taijihuabao.modules.enums.optenums.dept.DeptEnum;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.task.IdentityLink;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 人事部审批
 * @author xiaob
 */
@Component
public class PersonnelDeptListener implements ExecutionListener {

    @Resource
    private DeptUserMapper deptUserMapper;
    @Resource
    private ApprovalMapper approvalMapper;
    @Resource
    private ApprovalHistoryMapper approvalHistoryMapper;

    @Override
    public void notify(DelegateExecution execution) {
        //查询人事部
         List<DeptUserEntity> deptUserEntitys = deptUserMapper
                 .selectDeptByDeptCode(DeptEnum.PERSONNEL_DEPT.getCode());
        //考勤专员
        List<String> users = new ArrayList<>();
        for(DeptUserEntity due : deptUserEntitys){
            if (DeptRoleEnum.CheckInCommissioner.getCode().equals(due.getDeptRole())) {
                users.add(String.valueOf(due.getUserId()));
            }
        }
        //如果考勤人员请假，自己则不用审批
        String businesskey = execution.getProcessInstanceBusinessKey();
        ApprovalEntity approvalEntity = approvalMapper.selectById(Long.valueOf(businesskey));
        String applyUserId = String.valueOf(approvalEntity.getApplyUserId());
        if(!Objects.isNull(approvalEntity)){
            for(int i = 0;i<users.size();i++){
                if(applyUserId.equals(users.get(i))){
                    users.remove(users.get(i));
                    i--;
                }
            }
        }
        if(!CollectionUtils.isEmpty(users)){
            execution.setVariable("approverList", users);
        }
    }
}
